import { parse } from '@vue/compiler-sfc';
import { SourceLocation } from '@vue/compiler-core';

export default (source: string) => {
    const { template } = parse(source).descriptor;

    if (template) {
        const { type, content, loc } = template;

        if (['pug', 'jade'].includes(type)) {
            return replaceByPosition(source, normalizeTemplate(content), loc);

        }
    }

    return source;
}

function normalizeTemplate(template: string) {
    const indent = template.match(/^\n?(\s+)/)?.[1];

    if (indent) {
        return template
            .split('\n')
            .map(str => str.replace(indent, ''))
            .join('\n');
    }

    return template;
}

function replaceByPosition (source: string, replacer: string, config: SourceLocation) {
    const arr = source.split(/\n/);
    return [
        ...arr.slice(0, config.start.line - 1),
        arr[config.start.line - 1].slice(0, config.start.column) + replacer + arr[config.end.line - 1].slice(config.end.column - 1),
        ...arr.slice(config.end.line)
    ].join('\n');
}
